﻿//
// Copyright 2024 Exhunter Technology Co.Ltd2.
//

using System;
using System.Security.Cryptography;
using System.Text;
using X18.Framework.Core.Utils;

namespace X18.Framework.Core.Security
{
    /// <summary>
    /// 数据加密算法接口
    /// </summary>
    public abstract class IDataEncryptor
    {
        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="plainText">明文</param>
        /// <param name="key">密钥</param>
        /// <returns>密文</returns>
        public abstract byte[] EncryptToBytes(byte[] plainBytes, byte[] key = null);
        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="cipherText">密文</param>
        /// <param name="key">密钥</param>
        /// <returns>明文</returns>
        public abstract byte[] DecryptFromBytes(byte[] cipherBytes, byte[] key = null);

        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="plainText">明文</param>
        /// <param name="key">密钥</param>
        /// <returns>密文</returns>
        public virtual string EncryptToString(string plainText, byte[] key = null)
        {
            if (plainText.IsEmpty())
            {
                return string.Empty;
            }
            byte[] plainBytes = Encoding.Default.GetBytes(plainText);
            byte[] cipherBytes = EncryptToBytes(plainBytes, key);
            return Convert.ToBase64String(cipherBytes);
        }

        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="cipherText">密文</param>
        /// <param name="key">密钥</param>
        /// <returns>明文</returns>
        public virtual string DecryptFromString(string cipherText, byte[] key = null)
        {
            if (cipherText.IsEmpty())
            {
                return string.Empty;
            }
            byte[] cipherBytes = Convert.FromBase64String(cipherText);
            byte[] plainBytes = DecryptFromBytes(cipherBytes, key);
            return Encoding.Default.GetString(plainBytes, 0, plainBytes.Length);
        }

        /// <summary>
        /// 生成密码字符串
        /// </summary>
        public virtual string GenerateKey()
        {
            byte[] buffer = new byte[16];
            RandomNumberGenerator.Create().GetNonZeroBytes(buffer);
            string result = Convert.ToBase64String(buffer);
            return result;
        }
    }
}
